package com.lw.forkjoin;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author LW
 * @2020/8/21 11:35
 */
public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test();
        test2();
        test3();

    }
    public static void test(){
        long sum = 0;
        long start = System.currentTimeMillis();
        //JDK1.7的  分割符
        for (long i = 0L; i <= 10_0000_0000L; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间："+(end-start));
    }

    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间："+(end-start));
    }

    public static void test3(){
        Instant start = Instant.now();
//        long start = System.currentTimeMillis();
        // Stream并行流()
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L,Long::sum);
//        long end = System.currentTimeMillis();
        Instant end = Instant.now();
        System.out.println("sum=" +sum+ "时间: " + Duration.between(start, end).toMillis());
    }
}
